﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using yafc.Interface.Api;

namespace yafc.Data
{
	internal class PostPool
	{
		private Dictionary<string, Post> pool = new Dictionary<string,Post>();
		private PostPoolMgr.NewPostHandler newPostHandlers;

		public PostPoolMgr.NewPostHandler OnNewPost
		{
			get
				{ return newPostHandlers; }
			set
				{ newPostHandlers = value; }
		}
		public bool Add(Post value)
		{
			lock(pool)
			{
				if (pool.ContainsKey(value.post.id))
				{
					return false;
				}
				else
				{
					pool.Add(value.post.id, value);
					OnNewPost(value);
					return true;
				}
			}
		}
		public void Add(IEnumerable<Post> Posts)
		{
			lock(pool)
			{
				foreach (Post p in Posts)
				{
					if (!pool.ContainsKey(p.post.id))
					{
						pool.Add(p.post.id, p);
						OnNewPost(p);
					}
				}
			}
		}
		public bool TryGetValue(string id, out Post value)
		{
			lock(pool)
			{
				return pool.TryGetValue(id, out value);
			}
		}
	}

	public class PostPoolMgr
	{
		public delegate void NewPostHandler(Post NewPost);

		private static PostPoolMgr instance = new PostPoolMgr();
		private Dictionary<string, PostPool> pools = new Dictionary<string, PostPool>();

		private PostPoolMgr()
		{

		}

		public static PostPoolMgr getInstance()
		{
			return instance;
		}

		public bool Add(string ServId, Post P)
		{
			PostPool c;
			lock(pools)
			{
				if (!pools.TryGetValue(ServId, out c))
				{
					c = new PostPool();
					pools.Add(ServId, c);
				}
			}
			return c.Add(P);
		}
		public void Add(string ServId, IEnumerable<Post> Posts)
		{
			PostPool c;
			lock (pools)
			{
				if (!pools.TryGetValue(ServId, out c))
				{
					c = new PostPool();
					pools.Add(ServId, c);
				}
			}
			c.Add(Posts);
		}
		public bool TryGetValue(string ServId, string PostId, out Post value)
		{
			PostPool c;
			lock (pools)
			{
				if (!pools.TryGetValue(ServId, out c))
				{
					value = Post.Empty;
					return false;
				}
			}
			return c.TryGetValue(PostId, out value);
		}

		public void Subscribe(string ServId, NewPostHandler handler)
		{
			PostPool p;
			lock(pools)
			{
				if (!pools.TryGetValue(ServId, out p))
				{
					p = new PostPool();
					pools.Add(ServId, p);
				}
			}

			p.OnNewPost += handler;
		}
	}
}
